package com.web.web.request;

import com.web.web.session.RedisSession;
import com.web.web.session.SessionUser;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpSession;

/**
 * 用于controller方法入参自动封装器 HandlerMethodArgumentResolver
 */
public class SessionUserArugmentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return SessionUser.class.isAssignableFrom(methodParameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        RedisSessionHttpServletRequest request = nativeWebRequest.getNativeRequest(RedisSessionHttpServletRequest.class);
        if (request == null) {
            return null;
        }
        HttpSession session = request.getSession();
        if (session instanceof RedisSession) {
            if (methodParameter.getParameterType().equals(SessionUser.class)) {
                return ((RedisSession) session).getSessionUser();
            } else {
                return ((RedisSession) session).getSessionUser(methodParameter.getParameterType());
            }
        }
        return null;
    }

}
